class OrdersController < ApplicationController
 layout "background"
 before_filter:has_shop
 before_filter:has_order,
                :only=>[:shop_order_show,:user_order_show]

  def has_shop
    @shop=get_shop
    unless @shop
      redirect_to_shop_new
    end
  end
  
  def has_order
    @order = Order.find(params[:id])
    unless @order&&(@order.shop_id==get_shop().id||@order.user_id==session[:user_id])
      notice("你无权限查看该订单！")
      @order=nil
    else
      @items=LineItem.find(:all,:conditions=>["order_id=?",@order.id])
    end
  end
  
  def shop_order_list
    @orders=Order.find(:all,:conditions=>["shop_id=?",@shop.id])
  end
  
  def shop_order_show
    unless @order
      redirect_to(:action=>:shop_order_list)
    end
  end
  
  def shop_order_ps
    @order = Order.find(params[:id])
    unless @order&&@order.shop_id==@shop.id
      notice("你无权限查看该订单！")
      redirect_to(:action=>:shop_order_list)
    else
      if OrderManager.product_sent(@order)
        notice("成功发货！")
      else
        notice("发货失败！")
      end
      redirect_to(:action=>:shop_order_show,:id=>@order.id)
    end
  end
  
  def user_order_list
    @orders=Order.find(:all,:conditions=>["user_id=?",session[:user_id]])
  end
  
  def user_order_show
    unless @order
      redirect_to(:action=>"user_order_list")
    end
  end
  
  def new_order
    @cart=find_cart
  end
  
  def paid_to_seller
    order=Order.find(params[:id])
    if OrderManager.paid_to_seller(order)
      flash[:notice]="save successful!"
    else
      flash[:notice]="save fail!"
    end
    empty_cart
    redirect_to(:action=>:new_order)
  end
  
  private  
  def find_cart
    session[:cart] ||=Cart.new
  end
  
  def empty_cart
    session[:cart]=nil
  end
  
  def get_shop
    shop=Shop.find_by_user_id(session[:user_id])
    shop
  end
end
